package uit.nfcmenu.waiter.activities;


import java.io.File;
import java.util.ArrayList;

import uit.nfcmenu.waiter.controllers.ImageStoreManager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import uit.nfcmenu.models.DatabaseManager;
import uit.nfcmenu.models.IDataChangeHandler;
import uit.nfcmenu.models.MenuModel;
import uit.nfcmenu.receivers.NetworkStateReceiver;
import uit.nfcmenu.utils.ImageDownloader;
import uit.nfcmenu.utils.NetworkHelper;
import uit.nfcmenu.waiter.R;

public class MainMenuActivity extends Activity 
		implements IDataChangeHandler, OnClickListener {	
	public static String tag = MainMenuActivity.class.getSimpleName();

	private ImageView ivMenus[];
	private Button btnOrderList, btnLogout, btnRefresh;
	private LinearLayout mainLayout;

	private DatabaseManager mDBManager;
	ArrayList<MenuModel> mMenus;
	
	ProgressDialog progressDialog;
	boolean isSavedImgs = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_menu);
		
		progressDialog = new ProgressDialog(this).show(this, "Waiting...", null);
		initView();
		initData();		
	}
	
	private void initData() {
		mDBManager = DatabaseManager.getInstance(MainMenuActivity.this);
		mMenus = new ArrayList<MenuModel>();
		
		new Thread(new Runnable() {
			
			public void run() {				
				// get main menu
				mMenus = mDBManager.getMainMenusInDB();
				viewImages();	
				registerEventListener();
				viewHandler.sendEmptyMessage(0);
			}
		}).run();
	}
	
	Handler viewHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {	
			progressDialog.dismiss();
		}
	};
	
	private void initView() {
		// TODO Auto-generated method stub
		ivMenus = new ImageView[6];
		ivMenus[0] = (ImageView) findViewById(R.id.img_menu1);
		ivMenus[1] = (ImageView) findViewById(R.id.img_menu2);
		ivMenus[2] = (ImageView) findViewById(R.id.img_menu3);
		ivMenus[3] = (ImageView) findViewById(R.id.img_menu4);
		ivMenus[4] = (ImageView) findViewById(R.id.img_menu5);
		ivMenus[5] = (ImageView) findViewById(R.id.img_menu6);
//		ivMenus[6] = (ImageView) findViewById(R.id.img_menu7);
//		ivMenus[7] = (ImageView) findViewById(R.id.img_menu8);
		
		btnOrderList = (Button) findViewById(R.id.btnOrderList);
		btnLogout = (Button) findViewById(R.id.btnLogout);
		btnRefresh = (Button) findViewById(R.id.btnRefresh);
		mainLayout = (LinearLayout) findViewById(R.id.main_layout);
	}
	
	private void registerEventListener() {
		// TODO Auto-generated method stub
		int n = (mMenus.size() > ivMenus.length) ? ivMenus.length : mMenus.size();
		for (int i = 0; i < n; i++) {			
			final int index = i;
//			ivMenus[i].setOnClickListener(new OnClickListener() {
//				public void onClick(View v) {
//					// TODO Auto-generated method stub
//					launchListActivity(index);
//				}
//			});
			ivMenus[i].setOnTouchListener(new OnTouchListener() {
				float x,y;
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						x = event.getX();
						y = event.getY();
						return true;
					}
					if (event.getAction() == MotionEvent.ACTION_MOVE) {
						if (Math.abs(event.getX() - x) > 10 || Math.abs(event.getY() - y) > 10) {
							return false;
						}
					}
					if (event.getAction() == MotionEvent.ACTION_UP) {
						launchListActivity(index);
						return true;
					}
					return false;
				}
			});
		}
		
		btnOrderList.setOnClickListener(this);
		btnLogout.setOnClickListener(this);
		btnRefresh.setOnClickListener(this);
		mainLayout.setOnTouchListener(loadContainerOnTouchListener());
	}

	
	private void viewImages() {			
		// show
		int n = (mMenus.size() > ivMenus.length) ? ivMenus.length : mMenus.size();
		if (NetworkHelper.checkNetworkStatus(getBaseContext())) {
			ImageDownloader imgManager = new ImageDownloader();
			for (int i = 0; i < n; i++) {
				imgManager.download(mMenus.get(i).getImageLink(), ivMenus[i]);
			}
		} else {
			Log.i(tag, "no network connection, check in receiver="+NetworkStateReceiver.hasNetwork);
		}
		// test view image from sdcard
//		viewImageFromDB();
	}
	
	// fade-out for the finish()
	private void launchLoginActivity() {
//		Intent intent = new Intent(this, LoginActivity.class);
		finish();
//		runFadeOutAnimation();
		this.onBackPressed();
//		startActivity(intent);
	}

	// fade-in for startActivity()
	private void launchOrderListActivity() {
		Intent intent = new Intent(this, OrderListActivity.class);
//		runFadeInAnimation();
		startActivity(intent);
	}

//	private void runFadeInAnimation() {
//		Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
//		fadeIn.reset();
//		mainLayout.clearAnimation();
//		mainLayout.startAnimation(fadeIn);   
//	}
//
//	private void runFadeOutAnimation() {
//		Animation fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
//		fadeOut.reset();
//		mainLayout.clearAnimation();
//		mainLayout.startAnimation(fadeOut);   
//	}
	
	private void launchListActivity(int index) {
		int mainId = mMenus.get(index).getMenuID();
		String mainName = mMenus.get(index).getMenuName();
		Intent intent = new Intent(this, ListItemsActivity.class);
		Bundle b = new Bundle();
		b.putInt("mainId", mainId);
		b.putString("mainName", mainName);
		intent.putExtras(b);
		startActivity(intent);
	}
	
	public void onDataChanged() {
		// TODO Auto-generated method stub
		
	}

	public Context getContext() {
		// TODO Auto-generated method stub
		return getBaseContext();
	}

	float x;
	float y;
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Log.i(tag, "onTouch()");
		switch (v.getId()) {
		case R.id.btnOrderList:
			launchOrderListActivity();
			break;
		case R.id.btnLogout:
			launchLoginActivity();
			break;	
		case R.id.btnRefresh:
			Intent intent = new Intent(this, MainMenuActivity.class);
			finish();
			startActivity(intent);
			
			// test download ************
//			String name = "menu_";
//			if (!isSavedImgs) {
//				Log.i(tag, "save image to SDCard");
//				int n = (mMenus.size() > ivMenus.length) ? ivMenus.length : mMenus.size();
//				for (int i = 0; i < n; i++) {
//					Bitmap bitmap = Bitmap.createBitmap(ivMenus[i].getWidth(), ivMenus[i].getHeight(), Bitmap.Config.RGB_565);
//					Canvas canvas = new Canvas(bitmap);
//					ivMenus[i].draw(canvas);
//					String imageLink = ImageStoreManager.StoreByteImage(getBaseContext(), bitmap, 100, name+i, "/visualmenu");
//					mMenus.get(i).setImagePath(imageLink);
//				}
//				mDBManager.updateMenuToDB(mMenus);
//				isSavedImgs = true;
//			}
//			else {
//				viewImageFromDB();
//			}
			
			break;
		}
	}

	private void viewImageFromDB() {
		Log.i(tag, "view image from SDCard");
		mMenus = mDBManager.getMainMenusInDB();
		int n = (mMenus.size() > ivMenus.length) ? ivMenus.length : mMenus.size();
		for (int i = 0; i < n; i++) {
			// test view image from sdcard
//					String imageInSD = Environment.getExternalStorageDirectory().toString() 
//							+ "/visualmenu/"+name + i + ".jpg";
//			        File imageFile = new File(imageInSD);
		    Drawable d = Drawable.createFromPath(mMenus.get(i).getImageLink());
		    Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
//		        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
		    if (bitmap != null) {
		    	ivMenus[i].setImageBitmap(bitmap);
		    }
		}
	}
	
	public OnTouchListener loadContainerOnTouchListener() {
	    return new OnTouchListener() {
		    public boolean onTouch(View v, MotionEvent event) {
//		    	Log.i(tag, "new onTouch() x,y="+event.getX()+","+event.getY());
//		        LinearLayout layout = (LinearLayout) v;
//		        for(int i = 0; i < layout.getChildCount(); i++) {
//		            View view = layout.getChildAt(i);
//		            Rect outRect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
//		            if(outRect.contains((int)event.getX(), (int)event.getY())) {
//		                Log.i(this.getClass().getName(), String.format("Over view.id[%d]", view.getId()));
//		            }
//		        }
		    	if (event.getAction() == MotionEvent.ACTION_DOWN) {
					Log.i(tag, "onTouch() DOWN x,y = "+x+","+y);
					x = event.getX();
					y = event.getY();
				}

//				if (event.getAction() == MotionEvent.ACTION_MOVE) {
//					Log.i(tag, "onTouch() MOVE x,y = " + event.getX() + "," + event.getY());
//				}
		    	
				if (event.getAction() == MotionEvent.ACTION_UP) {
					Log.i(tag, "onTouch() UP x,y = " + event.getX() + "," + event.getY());
//					float dx = event.getX() - x; // < 0: left to right: next to OrderList; < 0: right to left: back to LogIn
//					float dy = Math.abs(event.getY() - y); // make sure this >0
//					Log.i(tag, "onTouch() UP dx,dy = " + dx + "," + dy);
					if (event.getX() < (x - 200)) { // right to left -> call OrderListActivity
						launchOrderListActivity();
					} else if (event.getX() > (x + 200)) { // left to right -> call LogInActivity
						launchLoginActivity();
					}
				}
				return true;
		    }
	    };
    }	
}
